package public

import (
	"github.com/dgrijalva/jwt-go"
	"rock/customer/initParam"
	"time"
)

var jwtSecret = []byte(initParam.JwtSecretConf.Secret)

type Claims struct {
	UserId     string `json:"userId"`
	Name       string `json:"name"`
	Avatar     string `json:"avatar"`
	DeviceUUID string `json:"device_uuid"` //设备唯一码
	jwt.StandardClaims
}

//生成token
func GenerateToken(userId, name, avatar, deviceUUID string) (string, error) {

	dd := time.Duration(initParam.JwtSecretConf.ExpireTime) * time.Hour

	nowTime := time.Now()
	expireTime := nowTime.Add(dd)

	claims := Claims{
		userId,
		name,
		avatar,
		deviceUUID,
		jwt.StandardClaims{
			ExpiresAt: expireTime.Unix(),
			Issuer:    "gin-blog",
		},
	}

	tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	token, err := tokenClaims.SignedString(jwtSecret)

	return token, err
}

//解析token
func ParseToken(token string) (*Claims, error) {
	tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
		return jwtSecret, nil
	})

	if tokenClaims != nil {
		if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
			return claims, nil
		}
	}

	return nil, err
}
